﻿using GatewayServerService.Data;
using Models.Common;
using MQTTnet.Client;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using Npgsql.Replication;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using UtilsBase;
using UtilsCache;
using UtilsMQ;
using UtilsMQ.Model;

namespace GatewayServerService.Mq
{

    public class ServiceMQTT_Client_Helper : MqttClientService
    {
        DBIotMqLog mqlog = new DBIotMqLog();
        //public static string mqtype = "";
        public ServiceMQTT_Client_Helper()
        {
            _topic = ConstantMqtt.gateway_server_topic;
            ConstantMqtt.ip = UtilAppsettingCache.getSetting("mqtt:hostName");
            ConstantMqtt.port = int.Parse(UtilAppsettingCache.getSetting("mqtt:port"));
            ConstantMqtt.username = UtilAppsettingCache.getSetting("mqtt:userName");
            ConstantMqtt.password = UtilAppsettingCache.getSetting("mqtt:password");
        }
        public void start()
        {

            new ServiceMQTT_Client_Helper().MqttClientStart();
        }
        /// <summary>
        /// 收到消息事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public override Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            //Console.WriteLine($"收到消息事件ApplicationMessageReceivedAsync：客户端ID=【{arg.ClientId}】接收到消息。Topic主题=【{arg.ApplicationMessage.Topic}】 消息=【{Encoding.UTF8.GetString(arg.ApplicationMessage.Payload)}】 qos等级=【{arg.ApplicationMessage.QualityOfServiceLevel}】");

            //这里不要新线程了，因为后面用到的handleEventLists线程不生效，跨线程用不了
            string message = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment);
            Task.Run(() =>
            {
                //判断客户端ID=【{arg.ClientId}】是否 dtu_20487
                //是的话
                //string[] messageSplit = message.Split("_");
                //if (messageSplit.Length > 2 && messageSplit[0] == "dtu")
                //{

                //    string ApplicationMessagePayload= BitConverter.ToString(arg.ApplicationMessage.Payload);
                //    new MQPayEvent_DTU().payEvent(message, ApplicationMessagePayload);
                //}
                //else
                //{
                //如果不是则下面处理方式
                //消息处理
                new ServiceMQPayEvent().payEvent(message);
                mqlog.writeMQLog(message, "receive", "true");
                //}
            });
            ///写日志


            return Task.CompletedTask;
        }

        public bool sendMsg(string topic, string data)
        {
            //Console.WriteLine($"发送消息事件。Topic主题=【{topic}】 消息=【{data}】 ");

            return new MqttClientService().Publish(topic, data);
        }
        public bool sendMsgByte(string topic, byte[] data)
        {
            return new MqttClientService().PublishByte(topic, data);
        }
    }
}
